<script setup lang="ts">
import { createNotification } from '@/utils/tool'
import { ref } from 'vue'
import {initDB} from '@/utils/tool'
chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  const getInstance = await initDB()
  if(request.type === 'contentComment'){
    const {name,comment,gift} = request
    getInstance().insert<Rack>({
      tableName: 'chart_message',
      data: {
        name,
        comment,
        gift
      }
    })
  }
})
// 开启或关闭助手
const handleClick =async (flag:string)=>{
  await chrome.storage.sync.set({ permissionLevel: selectValue.value,commentLevel:commentLevel.value })
  chrome.tabs.query(
    {
      active: true,
      currentWindow: true
    },
    (tabs) => {
      const message = {
        type:'popup',
        flag
      }
      // 发消息给contentscript
      chrome.tabs.sendMessage(tabs[0].id as number, message, res => {
        createNotification({title:'AI直播助手开关操作',message:'AI直播助手已'+(res==='start'?'开启':'停止')})
      })
    }
  )
}
// 选择欢迎等级
const selectValue = ref(8)
// 选择评论等级
const commentLevel = ref(0)
chrome.storage.sync.get(['permissionLevel','commentLevel']).then(res => {
  selectValue.value = res.permissionLevel||15
  commentLevel.value = res.commentLevel||5
})

// 在这里向 background 发起连接，之后会通过这个 port 来监听或者发送消息
// const port = chrome.runtime.connect();
// 打开新的标签页
const openNewTab = () => {
  // port.postMessage({ popupMessage: 'hello' })
  chrome.tabs.create({
    url: "src/onboarding/onboarding.html"
  })
}

// 重置数据库
const handleResetDB = async (flag: string) => {
  const getInstance = await initDB()
  if (flag === 'reset') {
    getInstance().delete_table('chart_message')
  }
}
</script>

<template>
  <a-row>
    <a-col :span="24" style="font-size: 20px;font-weight:bold;">抖音直播AI助手控制</a-col>
  </a-row>
  <a-row style="margin: 10px 0;">
    <a-col :span="8">欢迎等级设置：</a-col>
    <a-col :span="4">
      <a-select v-model:value="selectValue">
        <a-select-option v-for="item in 100" :key="item" :value="item">{{ item }}</a-select-option>
      </a-select>
    </a-col>
    <a-col :span="8">评论等级设置：</a-col>
    <a-col :span="4">
      <a-select v-model:value="commentLevel">
        <a-select-option v-for="item in 100" :key="item" :value="item">{{ item }}</a-select-option>
      </a-select>
    </a-col>
  </a-row>
  <div style="text-align: center;">
    <a-button style="margin-right: 50px;" type="primary" @click="handleClick('start')">开始</a-button>
    <a-button type="primary" @click="handleClick('stop')">停止</a-button>
  </div>
  <div style="text-align: center;margin-top: 10px;">
    <a-button type="primary" @click="openNewTab">打开场景</a-button>
    <a-button style="margin-left:10px" danger @click="handleResetDB('reset')">重置数据库</a-button>
  </div>
</template>

<style scoped>

</style>
